import re
import time

import requests
from loguru import logger

base_url = "http://api.eomsg.com/zc/data.php"
user_name = "yongza"
password = "abcd327668"


def login():
    url = f"{base_url}?code=login&user={user_name}&password={password}"
    response = requests.get(url)
    token = response.text
    logger.info(f"token: {token}")
    return token


def get_phone(token, phone=None):
    url = f"{base_url}?code=getPhone&token={token}&cardType=全部"
    if phone:
        # [实卡,虚卡,全部]
        url = f"{base_url}?code=getPhone&phone={phone}&token={token}&cardType=实卡"
    response = requests.get(url)
    phone = response.text
    logger.info(f"phone: {phone}")
    with open("phone.txt", "a") as f:
        f.write(phone + "\n")
    return phone


def get_msg(token, phone):
    max_retry = 10
    key_word = "企查查"
    while max_retry > 0:
        url = f"{base_url}?code=getMsg&token={token}&phone={phone}&keyWord={key_word}"
        response = requests.get(url)
        msg = response.text
        logger.info(f"msg: {msg}")
        if "尚未收到" in msg:
            max_retry -= 1
            time.sleep(5)
        else:
            content = re.findall(r'【企查查】您的验证码是(.*?)。', msg)
            return content[0]
    return None


if __name__ == "__main__":
    # token = login()
    # phone = get_phone(token, 16268645138)
    # get_msg(token, phone)
    cookies = [{'name': 'acw_tc', 'value': '8be3e64316939096537772676ef81bd45f4a40c927d4a43d2a5d2af785', 'path': '/',
      'domain': 'www.qcc.com', 'secure': False, 'httpOnly': True, 'expiry': 1693911453, 'sameSite': 'None'},
     {'name': 'QCCSESSID', 'value': 'dd8416337487eb6dae75a3d0aa', 'path': '/', 'domain': '.qcc.com', 'secure': False,
      'httpOnly': True, 'sameSite': 'None'},
     {'name': 'qcc_did', 'value': '6b8f6632-1a57-4482-bcfa-f841d7eaf739', 'path': '/', 'domain': '.qcc.com',
      'secure': True, 'httpOnly': False, 'expiry': 1780309655, 'sameSite': 'None'},
     {'name': 'UM_distinctid', 'value': '18a64e22afa11da-0b207e252f8d358-d525429-1fa400-18a64e22afbd09', 'path': '/',
      'domain': '.qcc.com', 'secure': False, 'httpOnly': False, 'expiry': 1709634458, 'sameSite': 'None'},
     {'name': 'CNZZDATA1254842228', 'value': '668877063-1693909658-%7C1693909658', 'path': '/', 'domain': 'www.qcc.com',
      'secure': False, 'httpOnly': False, 'expiry': 1709634458, 'sameSite': 'None'}]


